package com.example.backend.security.failure;

import com.example.backend.enums.ResultCodeEnum;
import org.springframework.http.MediaType;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @Description: 自定义异常处理
 */
//@Component
public class CustomSecurityExceptionHandler extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            // 设置响应状态码为 500
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

            // 构建错误信息并写入响应体
            String errorMessage = ResultCodeEnum.INTERNAL_SERVER_ERROR.getMessage();
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.getWriter().write(
                    "{\"code\": " + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ", \"message\": \"" + errorMessage + "\"}"
            );
        }
    }
}
